package com.wdz.controller;

import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wdz.http.Response;
import com.wdz.http.exceptionMonitor.GlobalExceptionHandler;
import com.wdz.kafka.Product;
import com.wdz.kafka.constant.Topics;
import com.wdz.kafka.entity.EmailEntity;
import com.wdz.user.entity.User;
import com.wdz.user.service.IUserService;
import com.wdz.utils.MD5Util;
import com.wdz.utils.RandomUtil;
import com.wdz.utils.RedisFieldName;
import com.wdz.utils.RedisUtil;
import com.wdz.utils.tenxunyuncos.COSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@RestController
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private Product product;

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Response register(@RequestBody User user){
        if(iUserService.selectCount(new EntityWrapper<User>().where("username={0}",user.getUsername()))>0){
            return Response.error("该用户名已被注册");
        }
        String salt = RandomUtil.makeSalt();
        user.setSalt(salt);
        user.setPassword(MD5Util.makePwd(user.getPassword(),salt));
        iUserService.insert(user);
        return Response.success();
    }
    /**
     * 注册用户 带有验证码
     * @param user
     * @return
     */
    @PostMapping("/register/{code}")
    public Response register(@RequestBody User user,@PathVariable Integer code){
        //先判断验证码是否正确
        RedisUtil redisUtil = RedisUtil.init();
        Map<Object,Object> codem = redisUtil.hmget(RedisFieldName.CODE);
        System.out.println(code.toString()+codem.get(user.getEmail()));
        if(!code.toString().equals(codem.get(user.getEmail()))){
            return Response.error("您输入的验证码有误，请重新输入！");
        }
        //判断邮箱是否已被注册
        if(iUserService.selectCount(new EntityWrapper<User>().where("email={0}",user.getEmail()))>0){
            return Response.error("该邮箱已注册账号");
        }
        if(iUserService.selectCount(new EntityWrapper<User>().where("username={0}",user.getUsername()))>0){
            return Response.error("该用户名已被注册");
        }
        String salt = RandomUtil.makeSalt();
        user.setSalt(salt);
        user.setPassword(MD5Util.makePwd(user.getPassword(),salt));
        iUserService.insert(user);
        user.setPassword(null);
        return Response.success(user);
    }
    /**
     * 发送验证码到邮箱
     */
    @PostMapping("/sendCodeToEmail")
    public Response sendCodeToEmail(@RequestParam String email) throws ExecutionException, InterruptedException {
        StringBuffer code = RandomUtil.getVerificationCode(6);
        EmailEntity emailEntity = new EmailEntity();
        emailEntity.setToEmail(email);
        emailEntity.setContent("<p>欢迎注册东哲个人博客，您的验证码是"+code+",请在3分钟内完成验证");
        emailEntity.setTitle("验证码");
        product.sendEmail(Topics.EMAILS,"sendEmail",emailEntity);
        RedisUtil redisUtil = RedisUtil.init();
        Map<String,Object> codem = new HashMap<String,Object>();
        codem.put(email,code);
        redisUtil.hmset(RedisFieldName.CODE,codem,3*60);
        return Response.success();
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Response login(@RequestParam String username,@RequestParam String password){
        User user = iUserService.selectOne(new EntityWrapper<User>().where("username={0}",username));
        if(user == null){
            return Response.error("用户不存在");
        }
        if(!user.getPassword().equals(MD5Util.makePwd(password,user.getSalt()))){
            return Response.error("密码错误");
        }
        user.setSalt(null);
        user.setPassword(null);
        return Response.success(user);
    }
    /**
     * 校验用户名是否已被使用
     */
    @PostMapping("/checkUsername")
    public Response checkUsername(@RequestParam String username){
        if(iUserService.selectCount(new EntityWrapper<User>().where("username={0}",username))>0){
            return Response.error("该用户名已被注册");
        }
        return Response.success();
    }
    /**
     * 根据id查询用户
     */
    @PostMapping("/queryUserInfoByID")
    public Response queryUserInfoByID(@RequestParam String id){
        return Response.success(iUserService.selectById(id));
    }
    /**
     * 修改用户信息
     */
    @PostMapping("/updateUserInfo")
    public Response updateUserInfo(@RequestBody User user){
        iUserService.update(user,new EntityWrapper<User>().where("id={0}",user.getId()));
        return Response.success();
    }

    @Value("${cos.regionName}")
    private String regionName;
    /**
     * 获取头像列表
     */
    @GetMapping("/getHeadphotos")
    public Response getHeadphotos(){
        String bn = "wdz-1258450135";
        COSService cosService = new COSService();
        List<Map<String, Object>> headphotoss = cosService.getFiels(regionName,bn,"/headphotos/");
        List<String> headphotos = new ArrayList<>();
        headphotoss.forEach(item->{
            if((long)item.get("fileSize") != 0) {
                headphotos.add(item.get("key").toString().substring(item.get("key").toString().indexOf("/")));
            }
        });
        return Response.success(headphotos);
    }
}
